//
//  UIImage+Utility.m
//  DGUtilityKit
//
//  Created by Jinxiao on 4/11/13.
//  Copyright (c) 2013 debugeek. All rights reserved.
//

#import "UIImage+Utility.h"

@implementation UIImage (Stretch)
+ (UIImage *)stretchImageWithName:(NSString *)name{
    
    UIImage *image = [UIImage imageNamed:name];
    return [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
}
//调整图片大小
+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
- (UIImage *)stretchableImageWithCapInsets:(UIEdgeInsets)capInsets
{
    if([self respondsToSelector:@selector(resizableImageWithCapInsets:)])
    {
        return [self resizableImageWithCapInsets:capInsets];
    }
    else
    {
        return [self stretchableImageWithLeftCapWidth:capInsets.left topCapHeight:capInsets.top];
    }
}

- (UIImage *)stretchableImageByCenter
{
    CGFloat leftCapWidth = floorf(self.size.width/2);
    if(leftCapWidth == self.size.width/2)
    {
        leftCapWidth--;
    }
    
    CGFloat topCapHeight = floorf(self.size.height/2);
    if(topCapHeight == self.size.height/2)
    {
        topCapHeight--;
    }
    
    return [self stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
}

- (UIImage *)stretchableImageByHeightCenter
{
    CGFloat topCapHeight = floorf(self.size.height/2);
    if(topCapHeight == self.size.height/2)
    {
        topCapHeight--;
    }
    
    return [self stretchableImageWithLeftCapWidth:0 topCapHeight:topCapHeight];
}

- (UIImage *)stretchableImageByWidthCenter
{
    CGFloat leftCapWidth = floorf(self.size.width/2);
    if(leftCapWidth == self.size.width/2)
    {
        leftCapWidth--;
    }
    
    return [self stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:0];
}

- (NSInteger)rightCapWidth
{
    return (NSInteger)self.size.width - (self.leftCapWidth + 1);
}

- (NSInteger)bottomCapHeight
{
    return (NSInteger)self.size.height - (self.topCapHeight + 1);
}

@end

@implementation UIImage (OrientationFix)

- (UIImage *)orientationFixedImage
{
    if(self.imageOrientation == UIImageOrientationUp)
    {
        return self;
    }
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch(self.imageOrientation)
    {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0.f);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0.f, self.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch(self.imageOrientation)
    {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0.f);
            transform = CGAffineTransformScale(transform, -1.f, 1.f);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0.f);
            transform = CGAffineTransformScale(transform, -1.f, 1.f);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    CGContextRef context = CGBitmapContextCreate(NULL, self.size.width, self.size.height, CGImageGetBitsPerComponent(self.CGImage), 0.f, CGImageGetColorSpace(self.CGImage), CGImageGetBitmapInfo(self.CGImage));
    CGContextConcatCTM(context, transform);
    switch(self.imageOrientation)
    {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(context, CGRectMake(0.f, 0.f, self.size.height, self.size.width), self.CGImage);
            break;
        default:
            CGContextDrawImage(context, CGRectMake(0.f, 0.f, self.size.width, self.size.height), self.CGImage);
            break;
    }
    
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    CGContextRelease(context);
    CGImageRelease(imageRef);
    return image;
}

- (UIImage *)imageByScalingWithScale:(double)scale
{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.size.width*scale, self.size.height*scale), YES, [UIScreen mainScreen].scale);
    [self drawInRect:CGRectMake(0, 0, self.size.width*scale, self.size.height*scale)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

@end

@implementation UIImage (Color)

+ (UIImage *)imageWithColor:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(10.f, 10.f), NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [color set];
    CGContextFillRect(context, CGRectMake(0.f, 0.f, 10.f, 10.f));
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end

@implementation UIImage (Gradient)

+ (UIImage *)verticalGradientImageBySize:(CGSize)size topColor:(UIColor *)topColor bottomColor:(UIColor *)bottomColor
{
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CFMutableArrayRef colors = CFArrayCreateMutable(NULL, 3, NULL);
    CFArrayAppendValue(colors, [topColor CGColor]);
    CFArrayAppendValue(colors, [bottomColor CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, colors, NULL);
    CGPoint startPoint = CGPointMake(size.width/2, 0.f);
    CGPoint endPoint = CGPointMake(size.width/2, size.height);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient);
    CFRelease(colors);
    CGColorSpaceRelease(colorSpace);
    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return gradientImage;
}


@end

@implementation UIImage (Resize)

- (UIImage *)clippedImageByConstranedSize:(CGSize)constranedSize
{
    CGSize destSize = CGSizeMake(MIN(constranedSize.width, self.size.width), MIN(constranedSize.height, self.size.height));
    return [self resizedImage:destSize interpolationQuality:kCGInterpolationHigh];
}

- (UIImage *)resizedImageByConstranedSize:(CGSize)constranedSize
{
    CGSize size = self.size;
    
    CGSize destSzie = size;
    CGFloat ratio = size.width/size.height;
    
    if(size.width > size.height)
    {
        if(size.width < constranedSize.width)
        {
            destSzie.width = size.width;
            destSzie.height = size.height;
        }
        else
        {
            destSzie.width = constranedSize.width;
            destSzie.height = destSzie.width/ratio;
        }
    }
    else
    {
        if(size.height < constranedSize.height)
        {
            destSzie.width = size.width;
            destSzie.height = size.height;
        }
        else
        {
            destSzie.height = constranedSize.height;
            destSzie.width = destSzie.height * ratio;
        }
    }
    
    UIImage *newImage = [self resizedImage:destSzie interpolationQuality:kCGInterpolationHigh];
    return newImage;
}

- (UIImage *)resizedImage:(CGSize)newSize interpolationQuality:(CGInterpolationQuality)quality
{
    UIImage *fixedImage = [self orientationFixedImage];
    
    CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width*fixedImage.scale, newSize.height*fixedImage.scale));
    CGImageRef imageRef = fixedImage.CGImage;
    
    CGContextRef bitmap = CGBitmapContextCreate(NULL, newRect.size.width, newRect.size.height, CGImageGetBitsPerComponent(imageRef), 0, CGImageGetColorSpace(imageRef), CGImageGetBitmapInfo(imageRef));
    
    CGContextSetInterpolationQuality(bitmap, quality);
    
    CGContextDrawImage(bitmap, newRect, imageRef);
    
    CGImageRef newImageRef = CGBitmapContextCreateImage(bitmap);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:fixedImage.scale orientation:fixedImage.imageOrientation];
    
    CGContextRelease(bitmap);
    CGImageRelease(newImageRef);
    
    return newImage;
}

- (UIImage *)orientationFixedImage
{
    if(self.imageOrientation == UIImageOrientationUp)
    {
        return self;
    }
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch(self.imageOrientation)
    {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0.f);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0.f, self.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch(self.imageOrientation)
    {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0.f);
            transform = CGAffineTransformScale(transform, -1.f, 1.f);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0.f);
            transform = CGAffineTransformScale(transform, -1.f, 1.f);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    CGContextRef context = CGBitmapContextCreate(NULL, self.size.width, self.size.height, CGImageGetBitsPerComponent(self.CGImage), 0.f, CGImageGetColorSpace(self.CGImage), CGImageGetBitmapInfo(self.CGImage));
    CGContextConcatCTM(context, transform);
    switch(self.imageOrientation)
    {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(context, CGRectMake(0.f, 0.f, self.size.height, self.size.width), self.CGImage);
            break;
        default:
            CGContextDrawImage(context, CGRectMake(0.f, 0.f, self.size.width, self.size.height), self.CGImage);
            break;
    }
    
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    CGContextRelease(context);
    CGImageRelease(imageRef);
    return image;
}



+ (UIImage *)createOtherMerchantImage:(NSString *)str withBgImage:(UIImage *)image withFont:(CGFloat)fontSize withTextColor:(UIColor *)textColor

{
    
    //    UIImage *image = [ UIImage imageNamed:@"otherMerchantHeaderBg" ];
    
    CGSize size= CGSizeMake (image. size . width , image. size . height ); // 画布大小
    
    UIGraphicsBeginImageContextWithOptions (size, NO , 0.0 );
    
    [image drawAtPoint : CGPointMake ( 0 , 0 )];
    
    // 获得一个位图图形上下文
    
    CGContextRef context= UIGraphicsGetCurrentContext ();
    
    CGContextDrawPath (context, kCGPathStroke );
    
    //画自己想画的内容。。。。。
    
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    
    //    [str drawAtPoint : CGPointMake ( image. size . width * 0.4 , image. size . height * 0.4 ) withAttributes : @{ NSFontAttributeName :[ UIFont fontWithName : @"Arial-BoldMT" size : 50 ], NSForegroundColorAttributeName :[ UIColor blackColor ],NSParagraphStyleAttributeName:paragraphStyle} ];
    
    UIFont  *font = [UIFont boldSystemFontOfSize:fontSize];//定义默认字体
    //计算文字的宽度和高度：支持多行显示
    CGSize sizeText = [str boundingRectWithSize:size
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{
                                                  NSFontAttributeName:font,//设置文字的字体
                                                  NSKernAttributeName:@10,//文字之间的字距
                                                  }
                                        context:nil].size;
    
    //为了能够垂直居中，需要计算显示起点坐标x,y
    CGRect rect = CGRectMake((size.width-sizeText.width)/2, (size.height-sizeText.height)/2, sizeText.width, sizeText.height);
    
    
    [str drawInRect:rect withAttributes:@{ NSFontAttributeName :[ UIFont fontWithName : @"Arial-BoldMT" size : fontSize ], NSForegroundColorAttributeName :textColor,NSParagraphStyleAttributeName:paragraphStyle} ];
    
    //画自己想画的内容。。。。。
    
    // 返回绘制的新图形
    
    UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext ();
    
    UIGraphicsEndImageContext ();
    
    return newImage;
    
}


@end
